/*********************************************************************************
 *      Copyright:  (C) 2023 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  led.c
 *    Description:  This file for led.c.
 *                 
 *        Version:  1.0.0(2023年07月11日)
 *         Author:  Ling Yun <lingyun@email.com>
 *      ChangeLog:  1, Release initial version on "2023年07月11日 13时56分40秒"
 *                 
 ********************************************************************************/

#include "led.h"

int led_init(unsigned char gpio_chip,unsigned char gpio_offset)
{
	int 			ret;
	unsigned char	buf[16];

	if( gpio_chip < 0 || gpio_chip > 5 || gpio_chip>32)
	{
		printf("%s line [%d] %s() get invalid input arguments\n",__FILE__,__LINE__,__func__);
		return -1;
	}

	memset(buf,0x0,sizeof(buf));
	snprintf(buf,sizeof(buf),"/dev/gpiochip%d",gpio_chip-1);

	chip = gpiod_chip_open(buf);
	if(!chip)
	{
		printf("fail to open chip0\n");
		return -1;
	}

	line_led = gpiod_chip_get_line(chip,LED_OFFSET);
	if(!line_led)
	{
		printf("fail to get line_led\n");
		return -2;
	}

	ret = gpiod_line_request_output(line_led,"led_out",1);
	if(ret < 0 )
	{
		printf("fail to request line_led for output mode\n");
		return -3;
	}

	return ret;
}

int led_control(unsigned char cmd)
{
	int ret;

	if(cmd == LED_OFF)
	{
		ret = gpiod_line_set_value(line_led,0);
	}
	else if(cmd == LED_ON)
	{
		ret = gpiod_line_set_value(line_led,1);
	}
	if(ret<0)
	{
		printf("fail to set line_led value\n");
		return -1;
	}

	return ret;
}

int led_release(void)
{
	gpiod_line_release(line_led);
	gpiod_chip_close(chip);
}

